﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.Revit;
using YArchitech.Revit.Electric.Common;
using HYElectricSystemDiagram.DataStruct;
using HYElectricSystemDiagram.FormSet;
using HYRElectric.PowerSystem;

namespace HYElectricSystemDiagram.TMethod
{
	public class SystemDiagramDrawingControler
	{
		private ElecMachPara SortElecMachPara(ElecMachPara elec)
		{
			if (elec.lstNameE.Count == 1)
			{
				return elec;
			}
			for (int i = elec.lstNameE.Count - 1; i > 0; i--)
			{
				for (int j = 0; j < i; j++)
				{
					string strA = elec.lstElem[j].GetParameter("配电盘名称").AsString();
					string strB = elec.lstElem[j + 1].GetParameter("配电盘名称").AsString();
					if (string.Compare(strA, strB, true) > 0)
					{
						string value = elec.lstNameE[j];
						elec.lstNameE[j] = elec.lstNameE[j + 1];
						elec.lstNameE[j + 1] = value;
						string value2 = elec.lstName[j];
						elec.lstName[j] = elec.lstName[j + 1];
						elec.lstName[j + 1] = value2;
						Element value3 = elec.lstElem[j];
						elec.lstElem[j] = elec.lstElem[j + 1];
						elec.lstElem[j + 1] = value3;
						List<int> value4 = elec.lstlstElementId[j];
						elec.lstlstElementId[j] = elec.lstlstElementId[j + 1];
						elec.lstlstElementId[j + 1] = value4;
						Dictionary<int, List<Element>> value5 = elec.lstDicElement[j];
						elec.lstDicElement[j] = elec.lstDicElement[j + 1];
						elec.lstDicElement[j + 1] = value5;
					}
				}
			}
			return elec;
		}

		public SystemDiagramDrawingControler(ExternalCommandData cmdData, List<ElecMachPara> lstElec)
		{
			this.m_Revit = cmdData;
			this.m_Doc = this.m_Revit.Application.ActiveUIDocument.Document;
			this.lstElecMa = lstElec;
		}

		public SystemDiagramDrawingControler(ExternalCommandData cmdData, List<ElectricBoxData> _lstHouseBoxInfo)
		{
			this.m_Revit = cmdData;
			this.m_Doc = this.m_Revit.Application.ActiveUIDocument.Document;
			this.lstHouseBoxInfo = _lstHouseBoxInfo;
		}

		public Result DrawingSystemDiagramCmd(Selection sel, UserControlData1 UserControl)
		{
			try
			{
				bool firstShow = false;
				ViewDrafting draftingView = this.GetDraftingView(ref firstShow);
				if (draftingView != null)
				{
					this.RefreshView(draftingView, firstShow);
				}
				SystemGraphSet systemGraphSet = null;
				if (!this.ReadSystemDiagramSetting(ref systemGraphSet))
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
				XYZ xyz = new XYZ(0.0, 0.0, 0.0);
				try
				{
					xyz = sel.PickPoint("请选择系统图插入点！");
				}
				catch
				{
					YJKMessageBox.Information("没有选择布置点！");
					return Autodesk.Revit.UI.Result.Failed;
				}
				GraphicsStyle frameStyle = null;
				GraphicsStyle midLineStyle = null;
				GraphicsStyle thickStyle = null;
				GraphicsStyle fineStyle = null;
				GraphicsStyle tableThickStyle = null;
				GraphicsStyle tableFineStyle = null;
				this.GetLineStyle(systemGraphSet, ref frameStyle, ref midLineStyle, ref thickStyle, ref fineStyle, ref tableThickStyle, ref tableFineStyle);
				TextNoteType textNoteType = null;
				this.GetTextNoteType(systemGraphSet, ref textNoteType);
				int num = 0;
				List<string> list = new List<string>();
				foreach (ElecMachPara elecMachPara in this.lstElecMa)
				{
					XYZ xyz2 = xyz - XYZ.BasisY * 19800.0 / 304.8 * (double)num;
					if (!UserControl.blHeng)
					{
						xyz2 = xyz - XYZ.BasisY * 26000.0 / 304.8 * (double)num;
					}
					int num2 = 0;
					int num3 = 0;
					foreach (Element element in this.SortElecMachPara(elecMachPara).lstElem)
					{
						XYZ point = xyz2 + XYZ.BasisX * 26000.0 / 304.8 * (double)num3;
						if (elecMachPara.lstlstElementId[num2].Count == 0)
						{
							num2++;
						}
						else
						{
							bool flag = false;
							string elecName = this.GetElecName(elecMachPara, element, num3, ref flag);
							bool flag2 = false;
							using (List<string>.Enumerator enumerator3 = list.GetEnumerator())
							{
								while (enumerator3.MoveNext())
								{
									if (enumerator3.Current.Contains(element.Name) && flag)
									{
										flag2 = true;
										break;
									}
								}
							}
							if (!flag2)
							{
								list.Add(elecName);
								num3++;
								SystemDiagramDrawingKit systemDiagramDrawingKit = new SystemDiagramDrawingKit(elecName, point, this.m_Revit, this.m_ViewScale, this.m_SwitchLegendColor, frameStyle, midLineStyle, thickStyle, fineStyle, tableThickStyle, tableFineStyle, textNoteType, element, elecMachPara.lstlstElementId[num2], elecMachPara.lstName[num2], elecMachPara.lstNameE[num2], UserControl);
								if (UserControl.blHeng)
								{
									systemDiagramDrawingKit.DrawSystemDiagramH(systemGraphSet);
								}
								else
								{
									systemDiagramDrawingKit.DrawSystemDiagramS(systemGraphSet);
								}
								num2++;
							}
						}
					}
					num++;
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Information(ex.ToString());
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private string GetElecName(ElecMachPara elec, Element elem, int index, ref bool blAdd)
		{
			string text = elem.GetParameter("配电盘名称").AsString();
			string text2 = text;
			int count = elec.lstlstElementId[index].Count;
			List<string> list = new List<string>();
			list.Add(text2);
			double num = 0.0;
			foreach (int elementId in elec.lstlstElementId[index])
			{
				double electricMachi = GetElectricInfo.GetElectricMachi(this.m_Doc, elementId, text);
				num += electricMachi;
			}
			num = Math.Round(num, 2);
			for (int i = 0; i < elec.lstElem.Count; i++)
			{
				if (i != index)
				{
					string text3 = elec.lstElem[i].GetParameter("配电盘名称").AsString();
					int count2 = elec.lstlstElementId[i].Count;
					double num2 = 0.0;
					foreach (int elementId2 in elec.lstlstElementId[i])
					{
						double electricMachi2 = GetElectricInfo.GetElectricMachi(this.m_Doc, elementId2, text);
						num2 += electricMachi2;
					}
					num2 = Math.Round(num2, 2);
					if (count == count2 && num2 == num && text != text3)
					{
						list.Add(text3);
						blAdd = true;
					}
				}
			}
			if (list.Count == 1)
			{
				return text2;
			}
			list.Sort();
			string text4 = "";
			foreach (string str in list)
			{
				text4 = text4 + " " + str;
			}
			return text4;
		}

		public Result DrawingSystemDiagramCmd(Selection sel, UserControlData2 UserControl)
		{
			try
			{
				bool firstShow = false;
				ViewDrafting draftingView = this.GetDraftingView(ref firstShow);
				if (draftingView != null)
				{
					this.RefreshView(draftingView, firstShow);
				}
				SystemGraphSet systemGraphSet = null;
				if (!this.ReadSystemDiagramSetting(ref systemGraphSet))
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
				XYZ xyz = new XYZ(0.0, 0.0, 0.0);
				try
				{
					xyz = sel.PickPoint("请选择系统图插入点！");
				}
				catch
				{
					YJKMessageBox.Information("没有选择布置点！");
					return Autodesk.Revit.UI.Result.Failed;
				}
				GraphicsStyle frameStyle = null;
				GraphicsStyle midLineStyle = null;
				GraphicsStyle thickStyle = null;
				GraphicsStyle fineStyle = null;
				GraphicsStyle tableThickStyle = null;
				GraphicsStyle tableFineStyle = null;
				this.GetLineStyle(systemGraphSet, ref frameStyle, ref midLineStyle, ref thickStyle, ref fineStyle, ref tableThickStyle, ref tableFineStyle);
				TextNoteType textNoteType = null;
				this.GetTextNoteType(systemGraphSet, ref textNoteType);
				int num = 0;
				foreach (ElectricBoxData elecBox in this.lstHouseBoxInfo)
				{
					new SystemDiagramDrawingHouse(xyz + XYZ.BasisX * 19500.0 / 304.8 * (double)num, this.m_Revit, this.m_ViewScale, this.m_SwitchLegendColor, frameStyle, midLineStyle, thickStyle, fineStyle, tableThickStyle, tableFineStyle, textNoteType, elecBox, UserControl).DrawSystemDiagram(systemGraphSet);
					num++;
				}
			}
			catch (Exception ex)
			{
				YJKMessageBox.Information(ex.ToString());
				return Autodesk.Revit.UI.Result.Failed;
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void RefreshView(ViewDrafting draftingView, bool firstShow)
		{
			try
			{
				if (this.m_Revit.Application.ActiveUIDocument.ActiveView.Id.IntegerValue != draftingView.Id.IntegerValue)
				{
					this.m_Revit.Application.ActiveUIDocument.ActiveView = draftingView;
					UIDocument activeUIDocument = this.m_Revit.Application.ActiveUIDocument;
					activeUIDocument.RefreshActiveView();
					if (firstShow)
					{
						UIView uiview = null;
						foreach (UIView uiview2 in activeUIDocument.GetOpenUIViews())
						{
							if (uiview2.ViewId.Equals(activeUIDocument.ActiveView.Id))
							{
								uiview = uiview2;
								break;
							}
						}
						if (uiview != null)
						{
							XYZ xyz = new XYZ(-100.0, -100.0, -5.0);
							XYZ xyz2 = new XYZ(100.0, 100.0, 5.0);
							uiview.ZoomAndCenterRectangle(xyz, xyz2);
						}
					}
				}
			}
			catch (Exception)
			{
			}
		}

		private ViewDrafting GetDraftingView(ref bool firstShow)
		{
			ViewDrafting viewDrafting = null;
			List<Element> list = RevitFilter.GetElementsOfType(this.m_Doc, typeof(ViewDrafting)).OfCategory(BuiltInCategory.OST_Views).ToList<Element>();
			List<string> list2 = new List<string>();
			foreach (Element element in list)
			{
				list2.Add(element.Name);
			}
			FormView formView = new FormView(list2);
			if (DialogResult.OK == formView.ShowDialog())
			{
				string strViewName = formView.strViewName;
				foreach (Element element2 in list)
				{
					if (element2.Name.CompareTo(strViewName) == 0)
					{
						viewDrafting = (element2 as ViewDrafting);
						this.m_ViewScale = viewDrafting.Scale;
						firstShow = false;
						return viewDrafting;
					}
				}
				if (viewDrafting == null)
				{
					if (!this.CreateViewDrafting(out viewDrafting))
					{
						firstShow = false;
						return viewDrafting;
					}
					Transaction transaction = new Transaction(this.m_Doc);
					transaction.Start("write extensibleStorage");
					viewDrafting.Name = strViewName;
					transaction.Commit();
				}
				firstShow = true;
				return viewDrafting;
			}
			return null;
		}

		private bool CreateViewDrafting(out ViewDrafting view)
		{
			Transaction transaction = new Transaction(this.m_Doc);
			transaction.Start("CreateViewDrafting");
			view = RevitViewExtension.CreateViewDrafting(this.m_Doc);
			if (view == null)
			{
				MessageBox.Show("创建绘图视图失败！");
				transaction.RollBack();
				return false;
			}
			BoundingBoxXYZ boundingBoxXYZ = new BoundingBoxXYZ();
			boundingBoxXYZ.Max = new XYZ(100.0, 100.0, 5.0);
			boundingBoxXYZ.Min = new XYZ(-100.0, -100.0, -5.0);
			view.CropBox = boundingBoxXYZ;
			view.Scale = this.m_ViewScale;
			view.ApplyViewTemplateParameters(this.m_Doc.ActiveView);
			view.get_Parameter(BuiltInParameter.VIEW_NAME).Set("盈建科电气系统图");
			transaction.Commit();
			return true;
		}

		private bool ReadSystemDiagramSetting(ref SystemGraphSet systemGraphSet)
		{
			string path = Path.Combine(Product.WorkingLocation, "SystemGraphSet.xml");
			if (!File.Exists(path))
			{
				string text = "SystemGraphSet.xml";
				string sourceFileName = AssistFunc.GetAppRootPath() + "\\Data\\ElectricalData\\" + text;
				string destFileName = Product.WorkingLocation + text;
				this.CopyFile(sourceFileName, destFileName);
			}
			ExportSystemXML exportSystemXML = new ExportSystemXML(path);
			systemGraphSet = exportSystemXML.LoadCSystemGraphSet(this.m_ViewScale);
			if (RevitVersion.Version != "2016")
			{
				systemGraphSet.TextHeight = 3.0;
			}
			if (systemGraphSet == null)
			{
				MessageBox.Show("读取系统图设置数据出错！");
				return false;
			}
			return true;
		}

		private void CopyFile(string sourceFileName, string destFileName)
		{
			try
			{
				File.Copy(sourceFileName, destFileName);
			}
			catch (Exception)
			{
			}
		}

		private bool GetLineStyle(SystemGraphSet systemGraphSet, ref GraphicsStyle frameStyle, ref GraphicsStyle midLineStyle, ref GraphicsStyle thickStyle, ref GraphicsStyle fineStyle, ref GraphicsStyle tableThickStyle, ref GraphicsStyle tableFineStyle)
		{
			Category category = this.m_Doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines);
			if (category == null)
			{
				return false;
			}
            string text = "系统图外框线 " + systemGraphSet.BusWidth.ToString("f0");
			string text2 = "系统图干线 " + systemGraphSet.BusWidth.ToString("f0");
			string text3 = "系统图粗线 " + systemGraphSet.WireWidth.ToString("f0");
            string text4 = "系统图细线 " + systemGraphSet.BusWidth.ToString("f0");
            string text5 = "系统图表格粗线 " + systemGraphSet.BusWidth.ToString("f0");
            string text6 = "系统图表格细线 " + systemGraphSet.BusWidth.ToString("f0");
            if (!category.SubCategories.Contains(text) && !this.CreateLineStyle((int)systemGraphSet.BusWidth, text, ref category))
			{
				return false;
			}
			if (!category.SubCategories.Contains(text2) && !this.CreateLineStyle((int)systemGraphSet.BusWidth, text2, ref category))
			{
				return false;
			}
			if (!category.SubCategories.Contains(text3) && !this.CreateLineStyle((int)systemGraphSet.WireWidth, text3, ref category))
			{
				return false;
			}
            if (!category.SubCategories.Contains(text4) && !this.CreateLineStyle((int)systemGraphSet.BusWidth, text4, ref category))
			{
				return false;
			}
            if (!category.SubCategories.Contains(text5) && !this.CreateLineStyle((int)systemGraphSet.BusWidth, text5, ref category))
			{
				return false;
			}
            if (!category.SubCategories.Contains(text6) && !this.CreateLineStyle((int)systemGraphSet.BusWidth, text6, ref category))
			{
				return false;
			}
			foreach (Element element in new FilteredElementCollector(this.m_Doc).OfClass(typeof(GraphicsStyle)))
			{
				GraphicsStyle graphicsStyle = element as GraphicsStyle;
				if (graphicsStyle != null)
				{
					if (graphicsStyle.Name.CompareTo(text) == 0)
					{
						frameStyle = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text2) == 0)
					{
						midLineStyle = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text3) == 0)
					{
						thickStyle = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text4) == 0)
					{
						fineStyle = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text5) == 0)
					{
						tableThickStyle = graphicsStyle;
					}
					if (graphicsStyle.Name.CompareTo(text6) == 0)
					{
						tableFineStyle = graphicsStyle;
					}
				}
			}
			return frameStyle != null && midLineStyle != null && thickStyle != null && fineStyle != null && tableThickStyle != null && tableFineStyle != null;
		}

		private bool CreateLineStyle(int lineWidth, string typeName, ref Category lineCategory)
		{
			if (this.m_Doc.Settings.Categories.get_Item(BuiltInCategory.OST_Lines) == null)
			{
				return false;
			}
			if (lineCategory.SubCategories.Contains(typeName))
			{
				return false;
			}
			Transaction transaction = new Transaction(this.m_Doc);
			bool result;
			try
			{
				transaction.Start("new line style");
				Category category = this.m_Doc.Settings.Categories.NewSubcategory(lineCategory, typeName);
				if (typeName.IndexOf("系统图外框线") != -1)
				{
					category.LineColor = this.m_ColorGreen;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else if (typeName.IndexOf("系统图干线") != -1)
				{
					category.LineColor = this.m_ColorPurple;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else if (typeName.IndexOf("系统图粗线") != -1)
				{
					category.LineColor = this.m_ColorCyan;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else if (typeName.IndexOf("系统图细线") != -1)
				{
					category.LineColor = this.m_ColorCyan;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else if (typeName.IndexOf("系统图表格粗线") != -1)
				{
					category.LineColor = this.m_ColorGreen;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else if (typeName.IndexOf("系统图表格粗线") != -1)
				{
					category.LineColor = this.m_ColorGreen;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				else
				{
					category.LineColor = this.m_ColorGreen;
					category.SetLineWeight(lineWidth, (Autodesk.Revit.DB.GraphicsStyleType)1);
				}
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = false;
			}
			return result;
		}

		private bool GetTextNoteType(SystemGraphSet systemGraphSet, ref TextNoteType textNoteType)
		{
			double num = AssistFunc.mmToFeet(systemGraphSet.TextHeight);
			double num2 = 0.7;
			double num3 = AssistFunc.mmToFeet(5.5);
			string text = "ElectricSystem " + AssistFunc.feetToMM(num).ToString("F2") + "mm";
			TextNoteType textNoteType2 = null;
			TextNoteType textNoteType3 = null;
			foreach (Element element in new FilteredElementCollector(this.m_Doc).OfClass(typeof(TextNoteType)).ToElements())
			{
				TextNoteType textNoteType4 = element as TextNoteType;
				if (textNoteType4 != null)
				{
					if (text.Equals(textNoteType4.Name))
					{
						textNoteType = textNoteType4;
						return true;
					}
					if (textNoteType3 == null)
					{
						textNoteType3 = textNoteType4;
					}
					else if (textNoteType4.Name.IndexOf("仿宋") != -1)
					{
						textNoteType3 = textNoteType4;
					}
					if (textNoteType4.Name.IndexOf("ElectricSystem") > -1)
					{
						Parameter parameter = textNoteType4.get_Parameter(BuiltInParameter.TEXT_SIZE);
						if (parameter != null)
						{
							double d = parameter.AsDouble();
							parameter = textNoteType4.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE);
							if (parameter != null)
							{
								double d2 = parameter.AsDouble();
								parameter = textNoteType4.get_Parameter(BuiltInParameter.LINE_COLOR);
								if (parameter != null)
								{
									int num4 = parameter.AsInteger();
									if (GeoUtil.IsEqual(num, d, 1E-05) && GeoUtil.IsEqual(num2, d2, 1E-05) && num4 == 0)
									{
										textNoteType = textNoteType4;
										return true;
									}
								}
							}
						}
					}
				}
			}
			if (textNoteType2 != null)
			{
				return true;
			}
			if (textNoteType3 == null)
			{
				return false;
			}
			Transaction transaction = new Transaction(this.m_Doc);
			bool result;
			try
			{
				transaction.Start("new textnote style");
				textNoteType = (textNoteType3.Duplicate(text) as TextNoteType);
				textNoteType.get_Parameter(BuiltInParameter.TEXT_FONT).Set("仿宋");
				textNoteType.get_Parameter(BuiltInParameter.LINE_COLOR).Set(0);
				textNoteType.get_Parameter(BuiltInParameter.TEXT_SIZE).Set(num);
				textNoteType.get_Parameter(BuiltInParameter.TEXT_WIDTH_SCALE).Set(num2);
				textNoteType.get_Parameter(BuiltInParameter.TEXT_TAB_SIZE).Set(num3);
				textNoteType.get_Parameter(BuiltInParameter.TEXT_BACKGROUND).Set(1);
				transaction.Commit();
				result = true;
			}
			catch (Exception)
			{
				if (transaction != null && transaction.HasStarted() && !transaction.HasEnded())
				{
					transaction.RollBack();
				}
				result = false;
			}
			return result;
		}

		private ExternalCommandData m_Revit;

		private Document m_Doc;

		public const string m_StrFrameidth = "系统图外框线";

		public const string m_StrBusWidth = "系统图干线";

		public const string m_StrThickWidth = "系统图粗线";

		public const string m_StrFineWidth = "系统图细线";

		public const string m_StrTablethickWidth = "系统图表格粗线";

		public const string m_StrTableFineWidth = "系统图表格细线";

		public const string m_StrTextNoteTypeName = "ElectricSystem";

		private int m_ViewScale = 100;

		private Autodesk.Revit.DB.Color m_ColorPurple = new Autodesk.Revit.DB.Color(byte.MaxValue, 0, byte.MaxValue);

		private Autodesk.Revit.DB.Color m_ColorGreen = new Autodesk.Revit.DB.Color(0, byte.MaxValue, 0);

		private Autodesk.Revit.DB.Color m_ColorCyan = new Autodesk.Revit.DB.Color(0, byte.MaxValue, byte.MaxValue);

		private Autodesk.Revit.DB.Color m_SwitchLegendColor = new Autodesk.Revit.DB.Color(0, byte.MaxValue, 0);

		private const int m_TextNoteColor = 0;

		private List<ElecMachPara> lstElecMa = new List<ElecMachPara>();

		private double offset = AssistFunc.mmToFeet(500.0);

		private List<ElectricBoxData> lstHouseBoxInfo;
	}
}
